package handler

import (
	"ecom-manager/cache"
	"ecom-manager/model"
	"ecom-manager/pkj"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	cache_key := "error_login_" + username
	cacheData, _ := cache.Rdb.Get(cache.Ctx, cache_key).Int()
	if cacheData >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次，禁止登录",
		})
		return
	}
	var user model.User
	err := model.DB.Where("username = ?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}

	if user.Password != pkj.Str(password) {
		cache.Rdb.Incr(cache.Ctx, cache_key)
		if cacheData == 2 {
			cache.Rdb.Set(cache.Ctx, cache_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次，封禁两小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登陆成功",
		"data": user,
	})
	return

}
func RoleNodeList(c *gin.Context) {
	rid := c.Query("rid")

	/*
		SELECT
		  *
		FROM
		  nodes
		  LEFT JOIN node_roles ON nodes.id = node_roles.nid
		WHERE
		  node_roles.rid = 1
	*/
	var node model.Node
	model.DB.Table("nodes ").
		Joins("LEFT JOIN  node_roles ON nodes.id = node_roles.nid").
		Where("node_roles.rid = ?", rid).
		Find(&node)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": node,
	})
}

func UserRoles(c *gin.Context) {
	uid := c.Query("uid")
	/*
		SELECT
		  *
		FROM
		  roles
		  LEFT JOIN user_roles ON roles.id = user_roles.rid
		WHERE
		  user_roles.uid = 1
	*/
	var role model.Role
	model.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON roles.id = user_roles.rid").
		Where(" user_roles.uid = ?", uid).
		Find(&role)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": role,
	})

}
func NodeRoleList(c *gin.Context) {
	rid := c.Query("rid")
	/*
		SELECT
		  *
		FROM
		  nodes
		  LEFT JOIN node_roles ON nodes.id = node_roles.nid
		WHERE
		  node_roles.rid = 1
	*/
	var node model.Node
	model.DB.Table("nodes ").
		Joins("LEFT JOIN  node_roles ON nodes.id = node_roles.nid").
		Where("node_roles.rid = ?", rid).
		Find(&node)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": node,
	})
}
func GoodAdd(c *gin.Context) {
	goodNum, _ := strconv.Atoi(c.PostForm("goodNum"))
	goodPrice, _ := strconv.Atoi(c.PostForm("goodPrice"))
	goodName := c.PostForm("goodName")
	goodCode := c.PostForm("goodCode")
	data := model.Good{
		//Model:     gorm.Model{},
		GoodCode:  goodCode,
		GoodName:  goodName,
		GoodNum:   goodNum,
		GoodPrice: goodPrice,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})

}
func GoodOrdersAdd(c *gin.Context) {
	ordersCode := c.PostForm("ordersCode")
	ordersNum, _ := strconv.Atoi(c.PostForm("ordersNum"))
	ordersPrice, _ := strconv.Atoi(c.PostForm("ordersPrice"))
	data := model.GoodOrders{
		//Model:       gorm.Model{},
		OrdersCode:  ordersCode,
		OrdersNum:   ordersNum,
		OrdersPrice: ordersPrice,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
}
func GoodOrdersList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	/*
		SELECT
		  goods.id AS Gid,
		  goods.good_code AS GoodCode,
		  goods.good_name AS GoodName,
		  goods.good_num AS GoodNum,
		  goods.good_price AS GoodPrice,
		  good_orders.orders_code AS OrdersCode,
		  good_orders.orders_num AS OrdersNum,
		  good_orders.orders_price AS OrdersPrice
		FROM
		  goods
		  LEFT JOIN good_orders ON goods.id = good_orders.gid
	*/
	var GoodOrders []model.GoodOrdersList
	cache_key := "page_size_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, cache_key).Result()
	if cacheData == "" {
		model.DB.Table("goods").
			Select("goods.id AS Gid",
				"goods.good_code AS GoodCode",
				"goods.good_name AS GoodName",
				"goods.good_num AS GoodNum",
				"goods.good_price AS GoodPrice",
				"good_orders.orders_code AS OrdersCode",
				"good_orders.orders_num AS OrdersNum",
				"good_orders.orders_price AS OrdersPrice").
			Joins(" LEFT JOIN good_orders ON goods.id = good_orders.gid").
			Offset(offset).Limit(size).Debug().Find(&GoodOrders)
		jsonData, _ := json.Marshal(&GoodOrders)
		cache.Rdb.Set(cache.Ctx, cache_key, jsonData, time.Second*120)
	} else {
		json.Unmarshal([]byte(cacheData), &GoodOrders)
	}

	var total int64
	model.DB.Model(model.GoodOrders{}).Debug().Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  GoodOrders,
		"total": total,
	})
}
func GoodOrderDetail(c *gin.Context) {
	id := c.Query("id")

	/*
		SELECT
		  goods.id AS Gid,
		  goods.good_code AS GoodCode,
		  goods.good_name AS GoodName,
		  goods.good_num AS GoodNum,
		  goods.good_price AS GoodPrice,
		  good_orders.orders_code AS OrdersCode,
		  good_orders.orders_num AS OrdersNum,
		  good_orders.orders_price AS OrdersPrice
		FROM
		  goods
		  LEFT JOIN good_orders ON goods.id = good_orders.gid
	*/
	var GoodOrders []model.GoodOrdersList
	cache_key := "detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, cache_key).Result()
	if cacheData == "" {
		model.DB.Table("goods").
			Select("goods.id AS Gid",
				"goods.good_code AS GoodCode",
				"goods.good_name AS GoodName",
				"goods.good_num AS GoodNum",
				"goods.good_price AS GoodPrice",
				"good_orders.orders_code AS OrdersCode",
				"good_orders.orders_num AS OrdersNum",
				"good_orders.orders_price AS OrdersPrice").
			Joins(" LEFT JOIN good_orders ON goods.id = good_orders.gid").
			Where("good_orders.id = ?", id).Debug().Find(&GoodOrders)
		jsonData, _ := json.Marshal(&GoodOrders)
		cache.Rdb.Set(cache.Ctx, cache_key, jsonData, time.Second*120)
	} else {
		json.Unmarshal([]byte(cacheData), &GoodOrders)
	}

	var total int64
	model.DB.Model(model.GoodOrders{}).Debug().Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  GoodOrders,
		"total": total,
	})
}
